package com.trial.personal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import android.view.ViewDebug.FlagToString;

public class MonitorService extends Service {

	public static Checker checkTread;
	//private BroadcastReceiver updateListener;
	
	public String pageUri = "";
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		checkTread = new Checker();
		Log.d("onReceive", "Service Created.");
	}

	@Override
	public synchronized void onDestroy() {
		
		checkTread.suspend();
		
		super.onDestroy();
	}

	@Override
	public synchronized void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.d("onReceive", "Service Started.");
		
		
    try {
		
			if(!checkTread.isRunning)
			{
				checkTread.start();
			}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	
	class Checker extends Thread
    {
    	public boolean isRunning = false;
    	private int notNum = 1;
		@Override
		public void run() {
			isRunning = true;
			while (isRunning) {
				try {
					InputStream data = getJSONData("http://jen777.0fees.net/api.php");
					
					String s = "";
					s = convertStreamToString(data);
					
					if(!s.startsWith("none"))
					{
						pageUri = s;
		                getJSONData("http://jen777.0fees.net/api.php?action=clear");
		                
		                NotificationManager manger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

		        		Notification notification = new Notification(R.drawable.icon,
		        				"New Url is fetched", System
		        						.currentTimeMillis());

		        		// The PendingIntent will launch activity if the user selects this
		        		// notification
		        		//Intent page = new Intent(getBaseContext(), PageActivity.class);
		        		//page.putExtra("URL", pageUri);
		        		
		        		
		        		Uri uri = Uri.parse(pageUri); 
		        		Intent page = new Intent(Intent.ACTION_VIEW, uri);
		        		

		        		String title = "Link shared by ...";

		        		
		        		PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(),
		        				0, page, 0);
		        		
		        		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		        		//notification.number = notNum;
		        		notNum++;
		        		notification.setLatestEventInfo(getBaseContext(), title, pageUri,
		        				contentIntent);
		        		
		        		manger.notify((int)Math.round(Math.random()*150), notification);

					}
					
					Log.d("Checker", "Service Running.");
					Thread.sleep(2000);	
				} catch (Exception e) {
					isRunning = false;
				}
				
				
			}
		}
		

	    public InputStream getJSONData(String url){
	        DefaultHttpClient httpClient = new DefaultHttpClient();
	        URI uri;
	        InputStream data = null;
	        try {
	            uri = new URI(url);
	            HttpGet method = new HttpGet(uri);
	            HttpResponse response = httpClient.execute(method);
	            data = response.getEntity().getContent();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        
	       return data;
	    }
	    
	    private String convertStreamToString(InputStream is) {
	        /*
	         * To convert the InputStream to String we use the BufferedReader.readLine()
	         * method. We iterate until the BufferedReader return null which means
	         * there's no more data to read. Each line will appended to a StringBuilder
	         * and returned as String.
	         */
	        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	        StringBuilder sb = new StringBuilder();
	 
	        String line = null;
	        try {
	            while ((line = reader.readLine()) != null) {
	                sb.append(line + "\n");
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                is.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	        return sb.toString();
	    }
	    
    	
    }
	
	
}
